// miniprogram/pages/Ranking/index.js
import {convertToChinaNum} from '../../utils/utils';

const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    staticUrl: app.globalData.staticUrl,
      rankingbyyear:{},
      logoUrl:app.globalData.imagelogourl,
      avatarUrl: app.globalData.imageunlogurl,
      currentTab:new Date().getFullYear(),
      currentpageheight:700,
      currentTabgroup:0,
      currentgroupcontentheight:0,
      baseimgaeUrl: app.globalData.imageBaseUrl,
      rankingbyyear_item:[],
      sponsorlogoes:[],
      topheight:app.globalData.navheight,
      selectarea:'全国',
      areas:[],
      pageno:1,
      isloading:false,
      isbottom:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

      
    /*wx.getLocation({
      type: 'wgs84',
      success: (result) => {
        const latitude = result.latitude
        const longitude = result.longitude
        const speed = result.speed
        const accuracy = result.accuracy
     
        wx.setStorageSync('location', {lng:longitude,lat:latitude});
      },
      fail: (res) => {},
      complete: (res) => {},
    })*/

        this.gettitles();
        this.setData({
          sponsorlogoes:app.globalData.sponsorlogoes,
          logoUrl:app.globalData.imagelogourl,
          baseimgaeUrl: app.globalData.imagebaseUrl,
        });
        console.log(this.data.baseimgaeUrl);
        var that = this;
        if(!this.data.sponsorlogoes){
          app.getlogoes(function(res){
            if(res.data.data){
              console.log("sponsorlogoes");
              console.log(res.data.data);
              that.setData({sponsorlogoes:res.data.data.loges});
          app.globalData.sponsorlogoes = that.data.sponsorlogoes.loges;
          if(res.data.data.ads ){
            app.globalData.bannerAd = res.data.data.ads;
            wx.setStorageSync('AD',  app.globalData.bannerAd);
          }
          else{
            app.globalData.bannerAd ="";
            wx.setStorageSync('AD',  app.globalData.bannerAd);
          }
        }
         
          
          },0);
        };
        this.getranking();
        this.getIndexpics();
  },

 /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (typeof this.getTabBar === 'function' &&
    this.getTabBar()) {
    this.getTabBar().setData({
      selected: 3
    })
    };
    this.setData({  topheight:app.globalData.navheight,})
    console.log(this.data.topheight);
  
  },
  onResize:function(res) {
    this.onShow();
  },
  

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },


  gettitles(selectyear){
    var year = selectyear?selectyear : new Date().getFullYear();
    var startyear = 2024 ;
    
    var content = year;//'第' +  convertToChinaNum(year-startyear +1 ) + '届';
    this.setData({title:content} );
    return content;
},


///获取首页图片
getIndexpics() {
  var that = this;
 
  
  app.getIndexpics(
    function(res){
        if(res.data.data.news){
          var indexpageUrl= [];
          var thurmbs = res.data.data.news;
          for(var index= 0;index<thurmbs.length;index++)
          {
            indexpageUrl.push(thurmbs[index]);
          }
            that.setData({indexpageUrl:indexpageUrl});
            console.log("that.data.indexpageUrl");
            console.log(that.data.indexpageUrl);
        }
        else{
          console.log("that.data.indexpageUrl:[]");
          that.setData({indexpageUrl:[]});
        }
    })
  

},


  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  // 下拉刷新方法
  onPullDownRefresh: function () {
    // 显示标题栏进度条效果
    wx.showNavigationBarLoading();

    this.setData({
      pageno:1,
      isloading:false,
      isbottom:false,
    })
   this.getranking(this.data.currentTab);
    
    // 取消标题栏进度条效果
    wx.hideNavigationBarLoading();
    // 取消页面刷新动画
    wx.stopPullDownRefresh();

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getranking(this.data.currentTab);
  },

  /**
   * 用户点击右上角分享
   */
  /*
  onShareAppMessage: function (options) {
    var that = this;
    // 设置菜单中的转发按钮触发转发事件时的转发内容
    var shareObj = {
      title:   app.langpagcke.apptitle[0] + '排名榜-'  + " " + app.langpagcke.apptitle[1] + '官方小程序' , // 默认是小程序的名称(可以写slogan等)
      path: '/pages/Ranking/index', // 默认是当前页面，必须是以‘/’开头的完整路径
      imageUrl:'/images/thurmb.png',
      //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {
          console.log(res);
        }
      },
      fail: function () {
        // 转发失败之后的回调
        if (res.errMsg == 'shareAppMessage:fail cancel') {
          // 用户取消转发
        } else if (res.errMsg == 'shareAppMessage:fail') {
          // 转发失败，其中 detail message 为详细失败信息
        }
      },
      complete: function () {
        // 转发结束之后的回调（转发成不成功都会执行）
      }

    };
    // 来自页面内的按钮的转发
    if (options.from == 'button') {
      var eData = options.target.dataset;
      console.log(eData.id); // shareBtn
      // 此处可以修改 shareObj 中的内容
     
    }
    // 返回shareObj
    return shareObj;
  },*/
 /**
   * 用户分享朋友圈
   */
  /*
  onShareTimeline(){
  
    var that = this;
    // 设置菜单中的转发按钮触发转发事件时的转发内容
    var shareObj = {
      title:   app.langpagcke.apptitle[0]  + "-排名榜- " + app.langpagcke.apptitle[1] + '官方小程序' , // 默认是小程序的名称(可以写slogan等)
      query: 'userID='+ app.globalData.userInfo.userID , // 默认是当前页面，自定义页面路径中携带的参数，如 path?a=1&b=2 的 “?” 后面部分
      imageUrl:'/images/iconlogo.png',
      //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
    };
   
    // 返回shareObj
    return shareObj;
},*/
  
  ///获取排名
  getranking(year,isrefrash)
  {

    if(this.data.isloading){
      return;
    }
    if(this.data.isbottom){
      return;
    }
    var year =(year)?year:(new Date().getFullYear()) , pageno  = this.data.pageno;
    
    var that = this;
    if(!isrefrash){
      wx.showLoading({
        title: '加载中',
      })
    }
    else{

    }
    this.setData({isloading:true});
    app.getranking(year,"",this.data.selectarea,pageno,
      function(res){
        console.log(res);
          if(res.data.data){
            if(res.data.data.rankingleaders && res.data.data.rankingleaders.length>0){
              if(pageno == 1){
              that.setData({
                rankingbyyear:res.data.data,
                pageno:pageno+1
              })
             }
             else{
              var rankingbyyear  = that.data.rankingbyyear;
               var rankingleaders = rankingbyyear.rankingleaders[0].leaders;
               var newleaders = res.data.data.rankingleaders[0].leaders;
               rankingleaders = rankingleaders.concat(newleaders);
               rankingbyyear.rankingleaders[0].leaders=rankingleaders;
               that.setData({
                rankingbyyear:rankingbyyear,
                pageno:pageno+1
              })
             }
            }
            else{
              if(pageno >= 1){
                that.setData({
                  isbottom:true
                })
              }
            }
             that.fillheight();
            }
      },function(){  
        if(!isrefrash){
        wx.hideLoading();
       }
        that.setData({isloading:false});
      })
 
  },


  bindDateChange:function(e){
    console.log(e);
     this.setData({
       selectarea:this.data.rankingbyyear.areas[e.detail.value],
    });
    this.setData({
      pageno:1,
      isloading:false,
      isbottom:false,
    })
     this.getranking(this.data.currentTab);
     this.gettitles(this.data.currentTab);
  },

 //  选择年tab切换逻辑
 swichNavyear: function(e) {
   var that = this;
   if( that.data.currentTab === e.target.dataset.current ) {
      
       return false;
   } else {
       that.setData( {
           currentTab: e.target.dataset.current
       })
       this.setData({
        pageno:1,
        isloading:false,
        isbottom:false,
      })
       this.getranking(this.data.currentTab);
   }

   that.fillheight();
   this.gettitles(this.data.currentTab);
  },
  swichNav:function(e){
    var that = this;
    if( that.data.currentTabgroup === e.target.dataset.current ) {
       
        return false;
    } else {
        that.setData( {
          currentTabgroup: e.target.dataset.current
        })
        
       
    }



    that.fillheight();
  },
   bindChange: function( e ) {
      var that = this;
       that.setData( { currentTabgroup: e.detail.current });
       that.fillheight();
 
    },
    fillheight:function(){
      var that = this;
      // var yearmatcheslists = that.data.schuedelDataByMonth[this.data.currentTab].monthmatches;
     // var yearindex = that.data.schuedelDataByMonth[this.data.currentTab].yearindex;
       // var height=0;
 
     
       var query = wx.createSelectorQuery();
      
        query.select('#ranking'+that.data.currentTab+that.data.currentTabgroup).boundingClientRect();

         query.exec(function(rect){
          if(rect!= null && rect[0]!=null && rect[0].height != null){
            console.log(rect);
            that.setData({
              currentpageheight:rect[0].height
           }
            )
          }
         
        });
       
     
    },
 //点击用户名字或卡片 直接弹出球员介绍页面
 _openplayerinfo:function(e){

    
    let selectid = e.detail.selectid;
    wx.navigateTo({
      url: '../Players/playerinfo/index?selectid='+selectid,
    })
    
 },

  //搜索的方法
  _search:function(){
    let searchcontent = e.detail.searchcontent;
    wx.showToast({
      title: searchcontent,
      icon: 'none'
    })


},
///页面滚动事件
onPageScroll: function (e) {
 
  var idobj = "#rankinglisttop";
  var that = this;
  wx.createSelectorQuery().select(idobj).boundingClientRect(function (rect) {
   var top = rect.top;
    if (top <= 0) {
      that.setData({
        istop: true
      })
      if(!that.data.topheight){
        that.setData({  topheight:app.globalData.navheight,})
      }
    } else {
      that.setData({
        istop: false
      })
      }
  }).exec();

  wx.createSelectorQuery().select('#vrankingcontain'+that.data.currentTab).boundingClientRect(function (rect) {
     if(!rect){
       return ;
     }
   
    var top = rect.top;
    console.log(rect);
    console.log( that.data.topheight);
     if (top <= that.data.topheight) {
       that.setData({
        istopnav: true
       })
 
 
 
     } else {
       that.setData({
        istopnav: false
       })
       }
   }).exec();


},

 //取消事件
 _error() {
  this.selectComponent("#info").hidePopup();

},

    //确认事件
   _success(e) {
      this.selectComponent("#info").showPopup();
  }, 


})